package com.ai.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.File;
import java.nio.file.Paths;

@Configuration
@Slf4j
public class WebConfig  implements WebMvcConfigurer {

    @Value("${app.upload.dir:./uploads}")
    private String uploadDir;

    @Value("${app.chunk.dir:./chunks}")
    private String chunkDir;


    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*") // 允许所有来源
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*");
                //.allowCredentials(true);
    }


    // 在服务器上的话，会在jar包同级目录下创建 uploads、chunks文件夹
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 使用绝对路径
        String absoluteUploadDir = getAbsolutePath(uploadDir);
        String absoluteChunkDir = getAbsolutePath(chunkDir);
        // 提供上传文件的静态访问
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + absoluteUploadDir + "/");

        registry.addResourceHandler("/chunks/**")
                .addResourceLocations("file:" + absoluteChunkDir + "/");
    }

    @Bean
    public String uploadDir() {
        return createDirIfNotExists(uploadDir);
    }

    @Bean
    public String chunkDir() {
        return createDirIfNotExists(chunkDir);
    }

    private String  createDirIfNotExists(String path) {
        String absolutePath = getAbsolutePath(path);
        File dir = new File(absolutePath);
        if (!dir.exists()) {
            boolean created = dir.mkdirs();
            if (created) {
                log.info("filePath not exist: {}, create success", path);
            } else {
                System.err.println("创建目录失败: " + absolutePath);
                log.info("filePath not exist: {}, create dir fail...", path);
            }
        }
        return absolutePath;
    }

    private String getAbsolutePath(String path) {
        // 处理相对路径，转换为绝对路径
        if (path.startsWith("./") || path.startsWith(".\\")) {
            // 获取项目根目录
            String projectRoot = System.getProperty("user.dir");
            return Paths.get(projectRoot, path.substring(2)).toAbsolutePath().toString();
        } else if (!Paths.get(path).isAbsolute()) {
            // 如果不是绝对路径，转换为绝对路径
            return Paths.get(path).toAbsolutePath().toString();
        }
        return path;
    }
}
